package com.soft.collateral.interceptor;

import cn.hutool.core.util.StrUtil;
import com.soft.collateral.constant.MessageConstant;
import com.soft.collateral.exception.AccessTokenInvalidException;
import com.soft.collateral.exception.CollateralException;
import com.soft.collateral.utils.JwtHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @desc TODO
 * @date 2025/7/24
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    //在进入请求之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("uri = "+request.getRequestURI());

        //1.从请求头中，获取访问token令牌   请求头中设置Token信息  以Authorization作为键，以Bearer accessToken作为值
        String authorization = request.getHeader("Authorization");

        //2.访问令牌为空
        if(StrUtil.isEmpty(authorization)){
            throw new CollateralException(MessageConstant.TOKEN_EMPTY);
        }
        String token = authorization.substring(7);
        log.info("LoginInterceptor token = {}" , token);

        //3.验证访问令牌是否过期
        if(JwtHelper.isExpiration(token)){
            throw new AccessTokenInvalidException(MessageConstant.ACCESS_TOKEN_VERIFY_FAIL);
        }

        //4.验证访问令牌是否合法
        Long userId = JwtHelper.getUserId(token);
        if(userId==null){
            throw new CollateralException(MessageConstant.TOKEN_ILLEGAL);
        }

        //后续处理 userId  -> User

        //放行
        return true;
    }
}